package com.syyo.gulimall.auth.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.utils.MyHttpUtils;
import com.syyo.common.vo.MemberVo;
import com.syyo.gulimall.auth.feign.MemberFeign;

import com.syyo.gulimall.auth.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @ author: wang
 * @ date: 2021/4/15 14:19
 * @ Description: 处理社交登录请求
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeign memberFeign;


    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) {

        String client_id = "884198868";
        String client_secret = "548b76495265bfe5caa63afe282b98a5";
        String grant_type = "authorization_code";
        String redirect_uri = "http://auth.gulimall.com/oauth2.0/weibo/success";

        String url = "https://api.weibo.com/oauth2/access_token?" +
                "client_id=" + client_id +
                "&client_secret=" + client_secret +
                "&grant_type=" + grant_type +
                "&redirect_uri=" + redirect_uri + "&code=" + code;
        String s = MyHttpUtils.postJson(url);

        // 微博账号的token信息
        SocialUser socialUser = JSON.parseObject(s, SocialUser.class);

        // 判断第三方用户登录是否是第一次登录，第一次登录，就注册，不是第一次就查询
        MemberVo authlogin = memberFeign.authlogin(socialUser);
        if (authlogin != null) {
            // 登录成功，session默认发的令牌，作用域是在当前域，需要改成成父级域
            // 使用json序列化的方法将数据存入redis中
            session.setAttribute("loginUser", authlogin);
            System.out.println("=============");
            System.out.println(authlogin);
            return "redirect:http://gulimall.com";
        }

        return "redirect:http://auth.gulimall.com/login.html";
    }


}
